package cn.itrip.controller;

import cn.itrip.beans.dto.Dto;
import cn.itrip.beans.pojo.*;
import cn.itrip.beans.vo.order.ItripAddHotelOrderVO;
import cn.itrip.beans.vo.order.RoomStoreVO;
import cn.itrip.beans.vo.order.ValidateRoomStoreVO;
import cn.itrip.common.*;
import cn.itrip.service.itripHotel.ItripHotelService;
import cn.itrip.service.itripHotelOrder.ItripHotelOrderService;
import cn.itrip.service.itripHotelRoom.ItripHotelRoomService;
import javafx.scene.chart.ValueAxis;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Member;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: jxm
 * @Description:
 * @Date: 2020/3/18 22:35
 * @Version: 1.0
 */
@Controller
@RequestMapping("/api/hotelorder")
public class HotelOrderController {

    @Resource
    private ValidationToken validationToken;
    @Resource
    private ItripHotelService itripHotelService;
    @Resource
    private ItripHotelRoomService itripHotelRoomService;
    @Resource
    private ItripHotelOrderService itripHotelOrderService;
    @Resource
    private SystemConfig systemConfig;

    /**
     * 生成订单前,获取预订信息
     * @return
     */
    @RequestMapping(value = "/getpreorderinfo",method = RequestMethod.POST,produces = "application/json")
    @ResponseBody
    public Dto<RoomStoreVO> getPreOrderInfo(@RequestBody ValidateRoomStoreVO validateRoomStoreVO,
                                            HttpServletRequest request){

        String token = request.getHeader("token");
        String agent = request.getHeader("user-agent");
        try {
            if(!validationToken.validateToken(token,agent)){ //token验证无效
                return DtoUtil.returnFail("token验证无效,请重新登录","100000");
            }
            if(validateRoomStoreVO.getHotelId() == null || validateRoomStoreVO.getHotelId() == 0){
                return DtoUtil.returnFail("hotelId不能为空","100510");
            }
            if(validateRoomStoreVO.getRoomId()== null || validateRoomStoreVO.getRoomId() == 0){
                return DtoUtil.returnFail("roomId不能为空","100511");
            }
            if(validateRoomStoreVO.getCheckInDate() == null || validateRoomStoreVO.getCheckOutDate() == null){
                return DtoUtil.returnFail("入住和退房时间不能为空","100514");
            }
            if(validateRoomStoreVO.getCheckInDate().getTime() > validateRoomStoreVO.getCheckOutDate().getTime()){
                return DtoUtil.returnFail("入住时间不能大于退房时间","100514");
            }

            //封装数据到前端页面
            ItripHotel hotel = itripHotelService.getItripHotelById(validateRoomStoreVO.getHotelId());
            ItripHotelRoom hotelRoom = itripHotelRoomService.getItripHotelRoomById(validateRoomStoreVO.getRoomId());
            RoomStoreVO roomStoreVO = new RoomStoreVO();
            roomStoreVO.setCheckInDate(validateRoomStoreVO.getCheckInDate());
            roomStoreVO.setCheckOutDate(validateRoomStoreVO.getCheckOutDate());
            roomStoreVO.setCount(1);
            roomStoreVO.setHotelId(hotel.getId());
            roomStoreVO.setHotelName(hotel.getHotelName());
            roomStoreVO.setRoomId(hotelRoom.getId());
            roomStoreVO.setPrice(BigDecimal.valueOf(hotelRoom.getRoomPrice()));

            //查询库存
            Map<String,Object> params = new HashMap<>();
            params.put("startTime",validateRoomStoreVO.getCheckInDate());
            params.put("endTime",validateRoomStoreVO.getCheckOutDate());
            params.put("roomId",validateRoomStoreVO.getRoomId());
            params.put("hotelId",validateRoomStoreVO.getHotelId());
            List<ItripHotelTempStore> results = itripHotelOrderService.queryRoomStore(params);
            if(EmptyUtils.isNotEmpty(results) && results.get(0).getStore()>0){
                //去最低的库房数
                roomStoreVO.setStore(results.get(0).getStore());
                return DtoUtil.returnDataSuccess(roomStoreVO);
            }else{
                return DtoUtil.returnFail("暂时无房","100512");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail("系统异常","100517");

        }


    }

    /**
     * 修改订房日期验证是否有房
     * @return
     */
    @RequestMapping(value = "/validateroomstore",method = RequestMethod.POST,produces = "application/json")
    @ResponseBody
    public Dto<Map<String,Boolean>> validateRoomStore(@RequestBody ValidateRoomStoreVO validateRoomStoreVO,
                                            HttpServletRequest request){

        String token = request.getHeader("token");
        String agent = request.getHeader("user-agent");
        try {
            if(!validationToken.validateToken(token,agent)){ //token验证无效
                return DtoUtil.returnFail("token验证无效,请重新登录","100000");
            }
            if(validateRoomStoreVO.getHotelId() == null || validateRoomStoreVO.getHotelId() == 0){
                return DtoUtil.returnFail("hotelId不能为空","100515");
            }
            if(validateRoomStoreVO.getRoomId()== null || validateRoomStoreVO.getRoomId() == 0){
                return DtoUtil.returnFail("roomId不能为空","100516");
            }
            if(validateRoomStoreVO.getCheckInDate() == null || validateRoomStoreVO.getCheckOutDate() == null){
                return DtoUtil.returnFail("入住和退房时间不能为空","100514");
            }
            if(validateRoomStoreVO.getCheckInDate().getTime() > validateRoomStoreVO.getCheckOutDate().getTime()){
                return DtoUtil.returnFail("入住时间不能大于退房时间","100514");
            }
            if(validateRoomStoreVO.getCount() == null || validateRoomStoreVO.getCount() == 0){
                return DtoUtil.returnFail("所需房间数不能为空","100518");
            }
            Map<String,Object> params = new HashMap<>();
            params.put("startTime",validateRoomStoreVO.getCheckInDate());
            params.put("endTime",validateRoomStoreVO.getCheckOutDate());
            params.put("roomId",validateRoomStoreVO.getRoomId());
            params.put("hotelId",validateRoomStoreVO.getHotelId());
            params.put("count",validateRoomStoreVO.getCount());

            //第一种需求
            boolean result = itripHotelOrderService.validateRoomStore(params);
            //第二种需求（需要实际库存数）
            //Map<String,Object> output2 = itripHotelOrderService.validateRoomStore2(params);
            Map<String,Boolean> output = new HashMap<>();
            if(result){
                output.put("flag",result);
                return DtoUtil.returnDataSuccess(output);
                //第二种需求返回
                //return DtoUtil.returnDataSuccess(output2);
            } else {
                return DtoUtil.returnFail("房间库存不够","100518");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail("系统异常","100512");
        }

    }

    /**
     * 生成订单
     * @return
     */
    @RequestMapping(value = "/addhotelorder",method = RequestMethod.POST,produces = "application/json")
    @ResponseBody
    public Dto<Map<String,Object>> addHotelOrder(@RequestBody ItripAddHotelOrderVO itripAddHotelOrderVO,
                                                 HttpServletRequest request){
        String token = request.getHeader("token");
        String agent = request.getHeader("user-agent");
        try {
            if(!validationToken.validateToken(token,agent)){ //token验证无效
                return DtoUtil.returnFail("token验证无效,请重新登录","100000");
            }

            //验证库存
            Map<String, Object> validateStoreMap = new HashMap<String, Object>();
            validateStoreMap.put("startTime", itripAddHotelOrderVO.getCheckInDate());
            validateStoreMap.put("endTime", itripAddHotelOrderVO.getCheckOutDate());
            validateStoreMap.put("hotelId", itripAddHotelOrderVO.getHotelId());
            validateStoreMap.put("roomId", itripAddHotelOrderVO.getRoomId());
            validateStoreMap.put("count", itripAddHotelOrderVO.getCount());
            if(!itripHotelOrderService.validateRoomStore(validateStoreMap)){
                return DtoUtil.returnFail("库存不足","100507");
            }

            //封装表单属性
            ItripHotelOrder itripHotelOrder = new ItripHotelOrder();
            BeanUtils.copyProperties(itripAddHotelOrderVO,itripHotelOrder);//复制数据
            ItripUser itripUser = validationToken.getCurrentUser(token);
            itripHotelOrder.setUserId(itripUser.getId());//设置下单人
            itripHotelOrder.setCreatedBy(itripUser.getId());
            //住店相关人
            List<ItripUserLinkUser> linkUsers = itripAddHotelOrderVO.getLinkUser();
            if(EmptyUtils.isNotEmpty(linkUsers)){
                StringBuilder  builder = new StringBuilder("");
                for(int i = 0; ; ){
                    builder.append(linkUsers.get(i).getLinkUserName());
                    if(++i < linkUsers.size()){
                        builder.append(",");
                        continue;
                    }
                    break;
                }
                itripHotelOrder.setLinkUserName(builder.toString());
            }
            //入住天数
            int days = DateUtil.getBetweenDates(itripAddHotelOrderVO.getCheckInDate(),
                    itripAddHotelOrderVO.getCheckOutDate()).size()-1;
            itripHotelOrder.setBookingDays(days);
            //设置来自平台
            if(token.startsWith("token:PC-")){
                itripHotelOrder.setBookType(0);
            }else if(token.startsWith("token:MOBILE-")){
                itripHotelOrder.setBookType(1);
            }else{
                itripHotelOrder.setBookType(2);
            }
            //订单状态
            itripHotelOrder.setOrderStatus(0);
            //设置订单号 -- [ 机器码+日期+MD5（hotelId+roomId+当前时间的毫秒数+百万级的随机数）]
            StringBuilder md5 = new StringBuilder("");
            md5.append(itripHotelOrder.getHotelId());
            md5.append(itripHotelOrder.getRoomId());
            md5.append(System.currentTimeMillis());
            md5.append(Math.random()*1000000);
            String md5Str = MD5.getMd5(md5.toString(),6);
            StringBuilder orderBuilder = new StringBuilder("");
            orderBuilder.append(systemConfig.getMachineCode());
            orderBuilder.append(DateUtil.format(new Date(),"yyyyMMddHHmmss"));
            orderBuilder.append(md5Str);
            itripHotelOrder.setOrderNo(orderBuilder.toString());
            //设置订单类型
            itripHotelOrder.setOrderType(1);
            //设置订单金额
            itripHotelOrder.setPayAmount(itripHotelOrderService.
                    getOrderPayAmount(days*itripAddHotelOrderVO.getCount(),
                            itripAddHotelOrderVO.getRoomId()).doubleValue());

            //添加订单
            Map<String,Object> results = itripHotelOrderService.itriptxAddItripHotelOrder(itripHotelOrder,
                    itripAddHotelOrderVO.getLinkUser());
            return DtoUtil.returnDataSuccess(results);
        }catch (Exception e){
            e.printStackTrace();
            return DtoUtil.returnFail(" 生成订单失败","100505");
        }

    }


}
